import { login, logout, getInfo, getAppMenus } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// import baseRouter from '../../../mock/routeBase'
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  dbname: '',
  id: '',
}

const mutations = {
  SET_TOKEN: (state, token) => {
    // microApp.setGlobalData({city: 'HK'}, () => {
    //   console.log('数据已经发送完成')
    // })
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_DBNAME: (state, dbname) => {
    state.dbname = dbname
  },
}

const actions = {
  async login({ commit }, userInfo) {
    // console.log('store>user>login:', userInfo)
    try {
      let res = await login(userInfo)
      // console.log('store>user>login?res.data:', res.data)
      commit('SET_TOKEN', res.data)
      setToken(res.data)
      return '验证成功！'
    } catch (e) {
      return e
    }
  },

  // get user info
  async getInfo({ commit, state }) {
    try {
      let res = await getInfo()
      // console.log('store>user>getInfo:', res)
      //   {
      //     "passWord": "202cb962ac59075b964b07152d234b70",
      //     "createTime": "2024-02-28T03:53:52.780+0000",
      //     "phone": "13801234567",
      //     "roles": "[\"admin\",\"debug\"]",
      //     "dept": "01",
      //     "userName": "管理员",
      //     "userId": "D99C5DCC-EFC6-40AD-9C2B-66F3A1652FD8",
      //     "age": 0,
      //     "account": "admin"
      // }
      const { userName, userId, roles } = res.obj
      commit('SET_ROLES', JSON.parse(roles))
      commit('SET_NAME', userName)
      commit('SET_ID', userId)
      commit('SET_DBNAME', '1001')
      commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
      commit('SET_INTRODUCTION', '')

      const resMenus = await getAppMenus()
      const menu = JSON.parse(resMenus.list[0]['dvalue'])
      return res.list.concat(menu)

      // return baseRouter
    } catch (e) {
      return e
    }
  },

  // user logout
  async logout({ commit, state, dispatch }) {
    try {
      await logout()
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
    } catch (e) {
      console.log('logout err:', e)
      return e
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'
    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
